import { reactive, toRefs, ref, onMounted, onUnmounted } from 'vue'

// function useMousePosition() {
//     const x = ref(0)
//     const y = ref(0)

//     function update(e) {
//         x.value = e.pageX
//         y.value = e.pageY
//     }

//     onMounted(() => {
//         console.log('useMousePosition mounted')
//         window.addEventListener('mousemove', update)
//     })

//     onUnmounted(() => {
//         console.log('useMousePosition unMounted')
//         window.removeEventListener('mousemove', update)
//     })

//     return {
//         x,
//         y
//     }
// }

function useMousePosition() {
    const state = reactive({
        x: 0,
        y: 0
    })

    function update(e) {
        state.x = e.pageX
        state.y = e.pageY
    }

    // 组件挂载时 将鼠标位置实时同步到state
    onMounted(() => {
        console.log('useMousePosition mounted')
        window.addEventListener('mousemove', update)
    })

    // 组件卸载时 移除mousemove事件
    onUnmounted(() => {
        console.log('useMousePosition unMounted')
        window.removeEventListener('mousemove', update)
    })

    return toRefs(state)
}

export default useMousePosition
